package com.aydx.minirpc.core.client;


import io.netty.channel.Channel;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class ChannelPoolFactory<T extends Channel> implements PooledObjectFactory<Channel> {

    private NettyTcpClient nettyTcpClient;

    public ChannelPoolFactory(NettyTcpClient nettyTcpClient) {
        this.nettyTcpClient = nettyTcpClient;
    }

    @Override
    public PooledObject<Channel> makeObject() throws Exception {
        return new DefaultPooledObject<Channel>(this.nettyTcpClient.createChannel()) ;
    }

    @Override
    public void destroyObject(PooledObject<Channel> pooledObject) throws Exception {
        this.nettyTcpClient.destoryChannel(pooledObject.getObject());
    }

    @Override
    public boolean validateObject(PooledObject<Channel> pooledObject) {
        Channel channel=pooledObject.getObject();
        if(channel!=null && channel.isActive()&& channel.isOpen() && channel.isRegistered() && channel.isWritable()){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public void activateObject(PooledObject<Channel> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<Channel> pooledObject) throws Exception {

    }
}
